package com.dabai.iot.core.controller;

import com.dabai.common.core.domain.R;
import com.dabai.common.core.enums.YnEnum;
import com.dabai.common.web.core.BaseController;
import com.dabai.iot.core.dto.CustomMessageInput;
import com.dabai.iot.core.dto.PropertyMessageInput;
import com.dabai.iot.core.entity.DeviceEntity;
import com.dabai.iot.core.service.IDeviceService;
import com.dabai.iot.core.service.IMessageService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 消息发送接口
 *
 * @author kev1n
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/message")
public class MessageController extends BaseController {

    private final IDeviceService deviceService;
    private final IMessageService messageService;

    /**
     * 发送自定义消息到设备
     */
    @PostMapping("/sendCustom")
    @Operation(summary = "发送自定义消息到设备")
    public R<Void> sendCustom(@Valid @RequestBody CustomMessageInput customMessageInput) {
        DeviceEntity device = deviceService.getDeviceCacheById(customMessageInput.getDeviceId());
        if (device == null) {
            return R.fail("设备不存在");
        }
        if (!YnEnum.YES.getValue().equals(device.getIsOnline())) {
            return R.fail("设备不在线");
        }

        messageService.sendCustomMessage(device, customMessageInput);
        return toAjax(true);
    }

    /**
     * 发送属性消息到设备
     */
    @PostMapping("/sendProperty")
    @Operation(summary = "发送属性消息到设备")
    public R<Void> sendProperty(@Valid @RequestBody PropertyMessageInput propertyMessageInput) {
        DeviceEntity device = deviceService.getDeviceCacheById(propertyMessageInput.getDeviceId());
        if (device == null) {
            return R.fail("设备不存在");
        }
        if (!YnEnum.YES.getValue().equals(device.getIsOnline())) {
            return R.fail("设备不在线");
        }

        messageService.sendPropertyMessage(device, propertyMessageInput);
        return toAjax(true);
    }

}
